package com.yequan.nio;

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;

/**
 * @author yq
 * @date 2020/09/25
 */
public class ProcessDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
//        Thread.sleep(30000);
        long startTime = System.currentTimeMillis();
//        processTest();
        process2Test();
        long consumeTime = System.currentTimeMillis() - startTime;
        System.out.println("耗时:" + consumeTime + " ms");
//        Thread.sleep(30000);
    }

    public static void processTest() throws IOException {
//        Process process = Runtime.getRuntime().exec("ping 127.0.0.1 -n 100");
        Process process = Runtime.getRuntime().exec("java -jar unzip.jar E:\\TEMP\\4.zip E:\\TEMP\\nio\\ E:\\TEMP\\ant\\");
        InputStream inputStream = process.getInputStream();
        ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\TEMP\\process.txt");
        FileChannel channel = fileOutputStream.getChannel();
        channel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
        channel.close();
        fileOutputStream.close();
        readableByteChannel.close();
    }

    public static void process2Test() throws IOException {
        Process process = Runtime.getRuntime().exec("ping 127.0.0.1 -n 100");
//        Process process = Runtime.getRuntime().exec("java -jar unzip.jar E:\\TEMP\\4.zip E:\\TEMP\\nio E:\\TEMP\\ant");
        InputStream inputStream = process.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\TEMP\\process.txt");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.flush();
        }
        bufferedWriter.close();
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        outputStreamWriter.close();
        fileOutputStream.close();
        inputStream.close();
    }

}
